<template>
	<view class="chat-page">
		<u-navbar leftIcon=" " :placeholder="true" :bgColor="bgColor">
			<view class="navtitle" slot="center">
				社区
			</view>
			<view class="navright" slot="right">
				<view class="info" @click="gourl('/pages/chat/addressbook/index')">
					<view :class="{'newuserhot' : isHot}"></view>
					<image src="/static/chat/icon1.png" mode=""></image>
				</view>
				<view class="info"> 
					<image src="/static/chat/icon2.png" @click="show = !show" mode=""></image>
					<view class="seleinfo" v-if="show == true">
						<view @click="gourl('/pages/chat/adduser/index')">添加好友</view>
						<view @click="gourl('/pages/chat/addgroup/index')">创建群聊</view>
					</view>
				</view>
			</view>
		</u-navbar>
		<view v-if="list.length < 1">
			<u-empty mode="message" :marginTop="100" icon="http://cdn.uviewui.com/uview/empty/message.png">
			</u-empty>
		</view>
		<view v-else>
			<view class="chat-list" v-for="(item, index) in list" :key="index" @touchstart="onTouchStart(index)"
				@touchend="onTouchEnd(item,index)" :class="{ 'long-press': longPressIndex === index }"
				@click="onClick(item)">
				<view class="chat-left" v-if="item.conversationType == 1">
					<view v-if="item.latestMessage.messageType == 'RC:RcCmd'">
						<u--image :showLoading="true" v-if="item.latestMessage.content.user" radius="10"
							:src="item.latestMessage.content.user.portraitUri||'/static/chat/logo.png'"
							loadingIcon="/static/chat/logo.png" errorIcon="/static/chat/logo.png" width="55px"
							height="55px"></u--image>
					</view>
					<view v-else>
						<u--image :showLoading="true" radius="10"
							v-if="item.latestMessage.senderUserId == userinfo.member_id"
							:src="item.latestMessage.content.receivePortraitUri||'/static/chat/logo.png'"
							loadingIcon="/static/chat/logo.png" errorIcon="/static/chat/logo.png" width="55px"
							height="55px"></u--image>
						<u--image :showLoading="true" radius="10" v-else
							:src="item.latestMessage.content.sendPortraitUri||'/static/chat/logo.png'"
							loadingIcon="/static/chat/logo.png" errorIcon="/static/chat/logo.png" width="55px"
							height="55px"></u--image>
					</view>
				</view>
				<view class="chat-right" v-if="item.conversationType == 1">
					<view class="right-box" v-if="item.latestMessage.messageType == 'RC:RcCmd'">
						<view class="title" v-if="item.latestMessage.content.user">
							{{item.latestMessage.content.user.name}}
							<view class="istop" v-if="item.isTop==true"><u-icon name="arrow-up-fill" color="#98F083"
									size="12"></u-icon></view>
						</view>
						<view class="time">
							{{$u.timeFormat(item.latestMessage.sentTime, 'mm-dd hh:MM')}}
						</view>
					</view>
					<view class="right-box" v-else>
						<view class="title" v-if="item.latestMessage.senderUserId == userinfo.member_id">
							{{item.latestMessage.content.receiveName}}
							<view class="istop" v-if="item.isTop==true"><u-icon name="arrow-up-fill" color="#98F083"
									size="12"></u-icon></view>
						</view>
						<view class="title" v-else>
							{{item.latestMessage.content.sendName}}
						</view>
						<view class="time">
							{{$u.timeFormat(item.latestMessage.sentTime, 'mm-dd hh:MM')}}
						</view>
					</view>
					<view class="cont">
						<view v-if="item.latestMessage.messageType == 'RC:RcCmd'">
							<text v-if="userinfo.member_id == item.latestMessage.senderUserId">你撤回了1条消息</text>
							<text v-else>对方撤回了1条消息</text>
						</view>
						<view v-else-if="item.latestMessage.messageType == 'RC:ImgMsg'">
							[图片消息]
						</view>
						<view v-else>
							{{item.latestMessage.content.content}}
						</view>
						<view class="unread" v-show="item.unreadMessageCount > 0 && item.notificationLevel!=5">
							{{item.unreadMessageCount | fixNum}}
						</view>
					</view>
				</view>
				<view class="chat-left" v-if="item.conversationType == 3">
					<u--image :showLoading="true" radius="10"
						v-if="item.latestMessage.messageType == 'RC:RcCmd'&&item.latestMessage.content.user"
						:src="item.latestMessage.content.user.portraitUri||'/static/chat/logo.png'"
						loadingIcon="/static/chat/logo.png" errorIcon="/static/chat/logo.png" width="55px"
						height="55px"></u--image>
					<u--image :showLoading="true" radius="10" v-else
						:src="item.latestMessage.content.receivePortraitUri||'/static/chat/logo.png'"
						loadingIcon="/static/chat/logo.png" errorIcon="/static/chat/logo.png" width="55px"
						height="55px"></u--image>
				</view>
				<view class="chat-right" v-if="item.conversationType == 3">
					<view class="right-box" v-if="item.latestMessage.messageType == 'RC:RcCmd'">
						<view class="title" v-if="item.latestMessage.content.user">
							{{item.latestMessage.content.user.name}}
							<view class="istop" v-if="item.isTop==true"><u-icon name="arrow-up-fill" color="#98F083"
									size="12"></u-icon></view>
						</view>
						<view class="time">
							{{$u.timeFormat(item.latestMessage.sentTime, 'mm-dd hh:MM')}}
						</view>
					</view>
					<view class="right-box" v-else>
						<view class="title">
							{{item.latestMessage.content.receiveName}}
							<view class="istop" v-if="item.isTop==true"><u-icon name="arrow-up-fill" color="#98F083"
									size="12"></u-icon></view>
						</view>
						<view class="time">
							{{$u.timeFormat(item.latestMessage.sentTime, 'mm-dd hh:MM')}}
						</view>
					</view>
					<view class="cont">
						<view v-if="item.latestMessage.messageType == 'RC:RcCmd'">
							<text v-if="userinfo.member_id == item.latestMessage.senderUserId">你撤回了1条消息</text>
							<text v-else>有人撤回了1条消息</text>
						</view>
						<view v-else-if="item.latestMessage.messageType == 'RC:ImgMsg'">
							[图片消息]
						</view>
						<view v-else-if="item.latestMessage.messageType == 'RC:envelope'">
							[有新的红包]
						</view>
						<view v-else-if="item.latestMessage.messageType == 'RC:envelopelq'">
							{{item.latestMessage.content.sendName}}领取了红包
						</view>
						<view v-else-if="item.latestMessage.messageType == 'RC:VcMsg'">
							[语音消息]
						</view>
						<view v-else-if="item.latestMessage.messageType == 'RC:adduser'">
							{{item.latestMessage.content.addname}}加入了群聊
						</view>
						<view class="hiadd" v-else>
							{{item.latestMessage.content.content}}
						</view>
						<view class="unread" v-show="item.unreadMessageCount > 0&& item.notificationLevel!=5">
							{{item.unreadMessageCount | fixNum}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-popup :show="popupshow" @close="close" round="5" bgColor="#232526" mode="center" @open="open">
			<view class="popupbox">
				<view class="title">选择</view>
				<u-button style="color: #000;border-radius: 20rpx;" @click="godeile(liucunitem)"
					color="linear-gradient( 90deg, #C8F673 0%, #98F083 100%)" type="primary" text="删除会话"></u-button>
				<u-button v-if="liucunitem.isTop == false" style="color: #000;border-radius: 20rpx; margin-top: 30rpx;"
					@click="goup(liucunitem)" color="linear-gradient( 90deg, #C8F673 0%, #98F083 100%)" type="primary"
					text="消息置顶"></u-button>
				<u-button v-if="liucunitem.isTop == true" style="color: #000;border-radius: 20rpx; margin-top: 30rpx;"
					@click="godown(liucunitem)" color="linear-gradient( 90deg, #C8F673 0%, #98F083 100%)" type="primary"
					text="取消置顶"></u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bgColor: 'rgba(0,0,0,0.0)',
				list: [],
				userinfo: {},
				isHot: false,
				show: false,
				touchStartTime: 0,
				touchTimeout: null,
				longPressThreshold: 500, // 长按的阈值，单位毫秒
				longPressIndex: null, // 记录当前长按的项
				popupshow: false,
				liucunitem: {}
			}
		},
		filters: {
			fixNum(val) {
				return val > 99 ? '99+' : val
			},
		},
		onLoad() {
			// 消息监听
			const Events = this.$RongIMLib.Events
			this.$RongIMLib.addEventListener(Events.CONVERSATION, this.listener)
		},
		onShow() {
			this.userinfo = uni.getStorageSync('info');
			this.postnewuser()
			this.posttimlogin()
		},
		onUnload() {
			//移除消息监听
			const Events = this.$RongIMLib.Events
			this.$RongIMLib.removeEventListener(Events.MESSAGES, this.listener)
		},
		methods: {
			godown(item) {
				// 隐藏弹出框
				this.popupshow = false;
				const conversationType = item.conversationType; // 会话类型
				const targetId = item.targetId; // 目标用户 ID
				const isTop = false; // 取消置顶
				// 调用 RongIMLib 的 setConversationToTop 方法
				this.$RongIMLib.setConversationToTop({
					conversationType,
					targetId
				},isTop).then(({
					code
				}) => {
					console.log(code)
					// 检查是否成功设置会话置顶
					if (code === 0) {
						uni.showToast({
							title: '已取消！',
							icon: 'none'
						});
						this.posttimlogin(); // 调用 posttimlogin 方法
					} else {
						// 处理设置失败的情况
						uni.showToast({
							title: '取消置顶失败，请重试。',
							icon: 'none'
						});
					}
				}).catch((error) => {
					// 处理异常情况
					console.error('设置会话置顶时发生错误:', error);
					uni.showToast({
						title: '操作失败，请检查网络连接。',
						icon: 'none'
					});
				});
			},
			goup(item) {
				// 隐藏弹出框
				this.popupshow = false;

				const conversationType = item.conversationType; // 会话类型
				const targetId = item.targetId; // 目标用户 ID
				const isTop = true; // 设置置顶

				// 调用 RongIMLib 的 setConversationToTop 方法
				this.$RongIMLib.setConversationToTop({
					conversationType,
					targetId
				},isTop).then(({
					code
				}) => {
					// 检查是否成功设置会话置顶
					if (code === 0) {
						uni.showToast({
							title: '置顶成功！',
							icon: 'none'
						});
						this.posttimlogin(); // 调用 posttimlogin 方法
					} else {
						// 处理设置失败的情况
						uni.showToast({
							title: '置顶失败，请重试。',
							icon: 'none'
						});
					}
				}).catch((error) => {
					// 处理异常情况
					console.error('设置会话置顶时发生错误:', error);
					uni.showToast({
						title: '操作失败，请检查网络连接。',
						icon: 'none'
					});
				});
			},
			open() {
				// console.log('open');
			},
			close() {
				this.popupshow = false
				// console.log('close');
			},
			onTouchStart(index) {
				this.touchStartTime = Date.now();
				// 设置一个长按超时
				this.touchTimeout = setTimeout(() => {
					this.longPressIndex = index; // 设置长按标志
				}, this.longPressThreshold);
			},
			onTouchEnd(item, index) {
				// 清除超时计时器
				clearTimeout(this.touchTimeout);

				// 如果标志未被设置，说明是点击事件
				if (this.longPressIndex === index) {
					// 长按逻辑
					this.longtap(item);
				} else {
					// 点击逻辑
					this.onClick(item);
				}

				// 重置标志
				this.longPressIndex = null;
			},
			onClick(item) {
				// 处理点击逻辑
				this.gonavto(item);
			},
			godeile(item) {
				let app = this
				app.popupshow = false
				uni.showModal({
					title: '提示',
					content: '是否删除此会话！',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							let conversationType = ''
							const targetId = item.targetId;
							if (item.conversationType == 3) {
								conversationType = app.$RongIMLib.ConversationType.GROUP;
							}
							if (item.conversationType == 1) {
								conversationType = app.$RongIMLib.ConversationType.PRIVATE;
							}
							app.$RongIMLib.removeConversation({
								conversationType,
								targetId: targetId,
							}).then(res => {
								// 删除指定会话成功
								if (res.code === 0) {
									console.log(res.code)
									uni.showToast({
										title: '删除成功',
										icon: 'none'
									})
									app.posttimlogin()
								} else {
									console.log(res.code, res.msg)
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			longtap(item) {
				console.log(item)
				// 处理长按逻辑
				// this.show = true
				this.longPressIndex = null
				let app = this
				this.popupshow = true
				this.liucunitem = item
				// 这里可以添加其他长按逻辑
			},
			listener(msg) {
				console.log(msg)
				this.postnewuser()
				this.posttimlogin()
			},
			postnewuser() {
				this.$Request({
					method: 'POST',
					url: '/api/rong/getBeVerified',
					data: {
						use_id: this.userinfo.member_id,
					}
				}).then(res => {
					if (res.code == 1) {
						let list = res.data
						if (list.findIndex(e => e.status == 0) != -1) {
							this.isHot = true
						} else {
							this.isHot = false
						}
					}
				})
			},
			gourl(url) {
				this.show = false
				uni.navigateTo({
					url: url
				})
			},
			gonavto(item) {
				let name = ''
				if (item.conversationType == 3) {
					if (item.latestMessage.messageType == 'RC:RcCmd') {
						name = item.latestMessage.content.user.name
					} else {
						name = item.latestMessage.content.receiveName
					}
					uni.navigateTo({
						url: '/pages/chat/groupchat/index?groupid=' + item.targetId + '&name=' + name
					})
				} else {
					if (item.latestMessage.messageType == 'RC:RcCmd') {
						name = item.latestMessage.content.user.name
					} else {
						if (item.latestMessage.senderUserId == this.userinfo.member_id) {
							name = item.latestMessage.content.receiveName
						} else {
							name = item.latestMessage.content.sendName
						}
					}
					uni.navigateTo({
						url: '/pages/chat/chitchat/index?id=' + item.targetId + '&name=' + name
					})
				}

			},
			posttimlogin() {
				this.$RongIMLib.getConversationList().then(({
					code,
					data: conversationList
				}) => {
					if (code === 0) {
						console.log('获取会话列表成功', conversationList);

						// 对会话列表进行排序，将置顶的会话移动到列表顶部
						const sortedList = conversationList.sort((a, b) => {
							// 假设置顶的会话有一个 isTop 属性标记
							return (b.isTop ? 1 : 0) - (a.isTop ? 1 : 0);
						});

						this.list = sortedList;
					} else {
						console.log('获取会话列表失败: ', code);
						setTimeout(() => {
							this.posttimlogin();
						}, 1000);
					}
				});
			},
		}
	}
</script>

<style>
	page {
		background-color: #17191A;
	}
</style>
<style scoped lang="scss">
	.chat-page {
		.popupbox {
			width: 70vw;
			padding: 30rpx;

			.title {
				color: #fff;
				text-align: center;
				margin-bottom: 30rpx;
				font-size: 28rpx;
				font-weight: 600;
			}
		}

		.navtitle {
			color: #fff;
		}

		.navright {
			display: flex;
			align-items: center;

			.info {
				position: relative;

				image {
					width: 40rpx;
					height: 40rpx;
					margin-left: 30rpx;
				}

				.seleinfo {
					width: 200rpx;
					position: absolute;
					bottom: -130rpx;
					right: 0;
					background-color: #fff;
					padding: 0 10rpx;
					text-align: center;
					border-radius: 10rpx;

					view {
						padding: 10rpx 0;
					}

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: -18rpx;
						/* 将箭头向上偏移 */
						right: 10rpx;
						/* 将箭头向左偏移 */
						z-index: -1;
						transform: rotate(90deg);
						/* 将箭头旋转90度，使其朝向右上角 */
					}
				}
			}

			.newuserhot {
				width: 6px;
				height: 6px;
				border-radius: 100%;
				position: absolute;
				z-index: 9;
				top: 0;
				right: -2px;
				background-color: red;
			}
		}

		.long-press {
			background-color: rgb(29, 33, 35);
			/* 长按时的背景色 */
		}

		.chat-list {
			display: flex;
			align-items: center;
			padding: 30rpx;
			transition: background-color 0.3s;
			position: relative;
			border-bottom: 1rpx solid #2b2b2b;
			.upicon {
				position: absolute;
				left: 0;
				top: 0;
			}

			.chat-left {
				width: 18%;
			}

			.chat-right {
				width: 82%;

				.right-box {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.istop {
						margin-left: 10rpx;
					}

					.title {
						font-size: 28rpx;
						color: #fff;
						display: flex;
						align-items: center;
					}

					.time {
						font-size: 24rpx;
						color: #d6d6d6;
					}
				}

				.cont {
					font-size: 24rpx;
					color: #d6d6d6;
					margin-top: 20rpx;
					display: flex;
					.hiadd{
						max-width: 300rpx;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
					.unread {
						width: 30rpx;
						height: 30rpx;
						background-color: red;
						font-size: 18rpx;
						border-radius: 50%;
						text-align: center;
						line-height: 30rpx;
						margin-left: 20rpx;
					}
				}
			}
		}
	}
</style>